package com.eiei.handler;

import java.text.SimpleDateFormat;
import java.util.List;

import com.eiei.bean.MessageBean;
import com.eiei.manager.MessageManager;
import com.eiei.thread.BaseThread;
import com.eiei.utils.BlowFishUtils;
import com.eiei.utils.ConsoleUtils;
import com.eiei.utils.TimeSequenceUtils;

public class Handler {
	
	private static MessageManager manager = new MessageManager();
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static void cmdHandler(String cmd){
		
		if(cmd == null || cmd.length() == 0){
			return ;
		}
		
		if(cmd.startsWith("list")){
			String[] params = cmd.split(" ");
			if(params.length!=3){
				ConsoleUtils.output("错误命令，list的用法为：list 1 10");
				return;
			}
			String fristIndexStr = params[1];
			String sizeStr = params[2];
			try{
				Integer index = Integer.parseInt(fristIndexStr);
				Integer size = Integer.parseInt(sizeStr);
				List<MessageBean> list = manager.list(index, size);
				for(MessageBean m:list){
					if(m.getSender().indexOf("eiei")!=-1 && m.getReciver().indexOf("huahua")!=-1){
						ConsoleUtils.output("eiei    "+sdf.format(m.getCreateDate())+"\n\t"+BlowFishUtils.decrypt(m.getContent()));
					}else if(m.getSender().indexOf("huahua")!=-1 && m.getReciver().indexOf("eiei")!=-1){
						ConsoleUtils.output("丫头    "+sdf.format(m.getCreateDate())+"\n\t"+BlowFishUtils.decrypt(m.getContent()));
					}else{
						ConsoleUtils.output(m.getSender()+"->"+m.getReciver()+"   "+sdf.format(m.getCreateDate())+"\n\t"+BlowFishUtils.decrypt(m.getContent()));
					}
				}
				return;
			}catch(Exception e){
				ConsoleUtils.output("错误命令，list的用法为：list 数字 数字");
				return;
			}
		}else if("help".equals(cmd)){
			ConsoleUtils.outputHelp();
		}else if("clear".equals(cmd)){
			ConsoleUtils.clear();
		}else if(cmd.startsWith("send ")){
			try{
				String message = cmd.substring(5);
				if(message.trim().length()==0){
					ConsoleUtils.output("错误命令，send的用法为：send 内容");
					return;
				}
				ConsoleUtils.output("正在发送，请稍等。");
				MessageBean messageBean = new MessageBean();
				messageBean.setId(TimeSequenceUtils.getIdString());
				messageBean.setContent(BlowFishUtils.encrypt(message));
				manager.sendMessage(messageBean);
				ConsoleUtils.output("发送成功。");
			}catch(Exception e){
				ConsoleUtils.output("信息发送错误，请稍后再试一试。");
				return;
			}
		}else if("quit".equals(cmd)){
			ConsoleUtils.output("系统即将推出。");
			BaseThread.threadSleep(3);
			System.exit(0);
		}else if("count".equals(cmd)){
			try{
				int count = manager.count();
				ConsoleUtils.output("你现在有["+count+"]条未读信息。");
				return;
			}catch(Exception e){
				ConsoleUtils.output("查询出错，请稍后再试一试。");
				return;
			}
		}
		else{
			ConsoleUtils.output("["+cmd+"]为未知命令。");
		}
		
	}
	
}
